package com.xh.audit.service.impl;


import cn.hutool.extra.cglib.CglibUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xh.audit.entity.WorkPlan;
import com.xh.audit.entity.WorkPlanVersion;
import com.xh.audit.entity.table.WorkPlanVersionTableDef;
import com.xh.audit.mapper.WorkPlanMapper;
import com.xh.audit.service.WorkPlanService;
import com.xh.audit.service.WorkPlanVersionService;
import com.xh.common.R;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;

/**
 * <p>
 * 审计工作计划;一个计划多个项目 ,一个项目只有一个计划， 先有计划再到项目 ****重要****
 * (参照wps文件版本 保存调整记录) 服务实现类
 * </p>
 *
 * @author lhl
 * @since 2023-10-19
 */
@RequiredArgsConstructor
@Service
@Validated
public class WorkPlanServiceImp extends ServiceImpl<WorkPlanMapper, WorkPlan> implements WorkPlanService {
    private final WorkPlanVersionService workPlanVersionService;

    @Transactional
    @Override
    public boolean saveWorkPlan(WorkPlan workPlan) {
        boolean save = this.saveOrUpdate(workPlan);
        //查最新的记录
        R<WorkPlanVersion> latestWorkPlan = workPlanVersionService.getLatestWorkPlanById(workPlan.getId());

        WorkPlanVersion workPlanVersion = WorkPlanVersion.builder().build();
        CglibUtil.copy(workPlan, workPlanVersion);

        workPlanVersion.setGroupPlanId(workPlan.getId());

        if (latestWorkPlan.getResult() == 0) {
            workPlanVersion.setId(workPlan.getId() + "-" + (latestWorkPlan.getData().getVersion() + 1));
            workPlanVersion.setVersion((latestWorkPlan.getData().getVersion() + 1));
        } else {
            workPlanVersion.setId(workPlan.getId() + "-" + 0);
            workPlanVersion.setVersion(0);
        }
        //保存新记录
        workPlanVersionService.save(workPlanVersion);

        return save;
    }

    @Transactional
    @Override
    public void delWorkPlans(List<Integer> ids) {

        this.removeByIds(ids); //这个入参空集合 不会执行sql

        QueryWrapper queryWrapper = QueryWrapper.create()
                .and(WorkPlanVersionTableDef.WORK_PLAN_VERSION.GROUP_PLAN_ID.in(ids));
        workPlanVersionService.remove(queryWrapper);
    }
}
